package com.example.test_app.Util

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Environment
import android.provider.Settings
import androidx.fragment.app.FragmentActivity
import java.io.File


/**
 */
object PhotoUtil {

    private var isNeedCrop = false
    val REQUESTCODESTORAGE = 501
    /**
     *裁剪502
     */
    val REQUESTCODECROUP = 502
    /**
     * 上传503
     */
    val REQUESTCODELOAD = 503

    /**
     * 照片file
     */
    val PHOTO_FILE_NAME = "temp_photo" + System.currentTimeMillis().toString() + ".jpg"

    const val PERMISSION_CAMERA = 0
    const val PERMISSION_STORAGE = 1

    var isFirstStorageOpen = true
    var isFirstCameraOpen = true
    fun initPermission(){

    }

     fun crop(uri: Uri, activity: Activity, photoId: String) {
        val intent = Intent("com.android.camera.action.CROP")
        intent.setDataAndType(uri, "image/*")
        intent.putExtra("crop", "true")
        intent.putExtra("aspectX", 1)
        intent.putExtra("aspectY", 1)
        intent.putExtra("outputX", 600)
        intent.putExtra("outputY", 600)
        intent.putExtra("outputFormat", "JPEG")
        intent.putExtra("noFaceDetection", true)
        intent.putExtra("output", Uri.parse("file:///" + Environment.getExternalStorageDirectory().path + "/small" + photoId + ".jpg"))
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString())
        //跳转修改头像-上传503
        activity.startActivityForResult(intent, REQUESTCODELOAD)
    }

    /**
     * 相册选择
     */
    @SuppressLint("CheckResult")
    fun getPhotoLib(activity: FragmentActivity, isCropNeed: Boolean = false) {
        this.isNeedCrop = isCropNeed


        isFirstStorageOpen = false
        getSystemPhotoAlbum(activity)


    }


    private fun gotoPermission(activity: FragmentActivity) {
        //引导用户至设置页手动授权
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        val uri = Uri.fromParts("package", activity.applicationContext.packageName, null)
        intent.data = uri
        activity.startActivity(intent)
    }



    private fun hasSdcard(): Boolean {
        return if (Environment.getExternalStorageState() == "mounted") {
            true
        } else false
    }

    private fun getSystemPhotoAlbum(activity: Activity) {
        val intent = Intent("android.intent.action.PICK")
        intent.type = "image/*"
        //个人中心-修改用户信息-跳转修改头像-裁剪502
        activity.startActivityForResult(intent, REQUESTCODECROUP)
    }

    private fun getRealFilePath(context: Context, uri: Uri?): String? {
        if (uri == null) {
            return null
        }
        val scheme = uri.scheme
        var data: String? = null
        if (scheme == null) {
            data = uri.path
        } else if ("file" == scheme) {
            data = uri.path
        } else if ("content" == scheme) {
            val cursor = context.contentResolver.query(uri, arrayOf("_data"), null, null, null)
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    val index = cursor.getColumnIndex("_data")
                    if (index > -1) {
                        data = cursor.getString(index)
                    }
                }
                cursor.close()
            }
        }
        return data
    }

    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?, context: Context, photoId: String = ""): File? {
        if (requestCode == REQUESTCODECROUP && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                return data.data?.let { checkNeedCrop(context as Activity, it, photoId) }
            }
        } else if (requestCode == REQUESTCODESTORAGE  && resultCode == Activity.RESULT_OK) {
            //检查存储501
            if (PhotoUtil.hasSdcard()) {
                val imagePath = File(Environment.getExternalStorageDirectory(), "wohenok")
                if (!imagePath.exists()) {
                    imagePath.mkdirs()
                }
                return checkNeedCrop(context as Activity, Uri.fromFile(File(imagePath, PHOTO_FILE_NAME)), photoId)
            }

        } else if (requestCode == REQUESTCODELOAD && resultCode == Activity.RESULT_OK) {
            //上传展示
            val uri = Uri.parse("file:///" + Environment.getExternalStorageDirectory().path + "/small" + photoId + ".jpg")
            val filePath = PhotoUtil.getRealFilePath(context, uri)
            val f = File(filePath)
            return f
        }
        return null
    }

    private fun checkNeedCrop(context: Activity, uri: Uri, photoId: String):File?{
        if(isNeedCrop){
            PhotoUtil.crop(uri, context, photoId)
            return null
        }
        val filePath = PhotoUtil.getRealFilePath(context, uri)
        val f = File(filePath)
        return f
    }

}

